package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import controller.PipesController;
import web.SessionStatus;
/*
 * Allows uploads to be resumed, transfering binary streams using a content type of application/octet-stream
 * in blocks of 5242880 bytes
 */
public class AjaxResumableUploadServletProvider extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1458365345236667188L;
	private JSONObject json = new JSONObject();
	private PipesController pipesController;

	public AjaxResumableUploadServletProvider( PipesController pipesController ) {
		this.pipesController = pipesController;
	}

	protected void doGet( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException {

		doPost(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		// get the auth user variable
		String authuser = request.getParameter("authuser");
		
		// get the user variable
		String user = request.getParameter("user");
		
		// get the upload id - 88 character alpha numberic
		String upload_id = request.getParameter("upload_id");
		
		// get the file id (Range 000-999)
		String file_id = request.getParameter("file_id");

                // get the url
		String url = request.getRequestURI();

                // get the content type
		String content_type = request.getContentType();

                SessionStatus sessionStatus = new SessionStatus( authuser, user, upload_id, file_id, url, content_type );

		// get the response, a string containing the same id
		json = this.pipesController.upload( sessionStatus );

		// generate and send the response
		response.setContentType("application/json");
		response.setHeader("Cache-Control", "no-cache");
		response.getWriter().write( json.toString() );

	}

}
